import 'package:flutter/material.dart';
import 'package:reorderables/reorderables.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/models/user/feedback_obj.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/data_util.dart';
import 'package:xws/utils/dio_utils/qiniu_oss.dart';
import 'package:xws/utils/dio_utils/request/user_req.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/utils/tools_util.dart';
import 'package:xws/widgets/app_btn.dart';
import 'package:xws/widgets/app_img.dart';
import 'package:xws/widgets/app_text_field.dart';
import 'package:xws/widgets/safe_scaffold.dart';

/// 反馈
class FeedBack extends StatelessWidget {
  const FeedBack({Key? key, required this.feedbackObj}) : super(key: key);

  final FeedbackObj feedbackObj;

  /// 提交
  Future<void> _submit(BuildContext context) async {
    final String cr = feedbackObj.check();

    if (cr != 'success') {
      ct(cr);
      return;
    }

    loading(context);

    final bool up = await _uploadImgs();

    if (!up) {
      close(context);
      return;
    }

    final bool f = await feedback(feedbackObj);

    if (!f) {
      close(context);
      return;
    }

    close(context);

    st('提交成功');

    pop(context);
  }

  /// 上传图片
  Future<bool> _uploadImgs() async {
    if (feedbackObj.imageUrlList.isEmpty) return true;

    final List<String> r = await QiniuOSS.uploadFiles(
      feedbackObj.imageUrlList,
      Dir.feedback,
    );

    if (r.isEmpty) {
      et('图片上传失败');
      return false;
    }

    feedbackObj.imageUrlList = r;

    return true;
  }

  @override
  Widget build(BuildContext context) {
    return SafeScaffold(
      titleText: '意见反馈',
      actions: <Widget>[
        Padding(
          padding: const EdgeInsets.only(right: 10),
          child: AppBtn(onTap: () => _submit(context), text: '提交'),
        ),
      ],
      backgroundColor: white(context),
      body: ListView(
        padding: const EdgeInsets.all(20),
        children: <Widget>[
          _title(context),
          const SizedBox(height: 14),
          _description(context),
          const SizedBox(height: 14),
          _SelectImages(
            onSelect: (List<String> v) => feedbackObj.imageUrlList = v,
          ),
        ],
      ),
    );
  }

  Widget _title(BuildContext context) {
    return AppTextField(
      hintText: '输入标题...',
      maxLength: 50,
      onChanged: (String v) => feedbackObj.title = v,
      fillColor: canvas(context),
      border: OutlineInputBorder(
        borderSide: BorderSide.none,
        borderRadius: BorderRadius.circular(6),
      ),
    );
  }

  Widget _description(BuildContext context) {
    return AppTextField(
      hintText: '意见描述...',
      height: 160,
      maxLines: 200,
      maxLength: 10,
      onChanged: (String v) => feedbackObj.content = v,
      fillColor: canvas(context),
      border: OutlineInputBorder(
        borderSide: BorderSide.none,
        borderRadius: BorderRadius.circular(6),
      ),
    );
  }
}

/// 选择图片
class _SelectImages extends StatefulWidget {
  const _SelectImages({
    Key? key,
    this.maxCount = 6,
    this.onSelect,
  }) : super(key: key);

  @override
  _SelectImagesState createState() => _SelectImagesState();

  final int maxCount;
  final Function(List<String>)? onSelect;
}

class _SelectImagesState extends State<_SelectImages> with SafeState<_SelectImages> {
  final List<String> _images = <String>[];

  final double _itemSize = (sw - 60) / 3 - 0.6;

  /// 图片总数
  int get _total => _images.length;

  /// 预览
  Future<void> _preView(int index, String tag) async {
    await assetsViewer(context, _images, initIndex: index, heroTag: tag);
  }

  /// 选择图片
  Future<void> _pickImages() async {
    final List<String>? imgs = await pickImgs(context, max: widget.maxCount - _images.length);
    if (imgs != null && imgs.isNotEmpty) {
      safeSetState(() => _images.addAll(imgs));
      widget.onSelect?.call(_images);
    }
  }

  /// 移除图片
  Future<void> _removeImg(int index) async {
    _images.removeAt(index);
    safeSetState(() {});
    widget.onSelect?.call(_images);
  }

  @override
  Widget build(BuildContext context) {
    return _buildImgList;
  }

  /// 图片列表
  Widget get _buildImgList {
    return ReorderableWrap(
      spacing: 10,
      runSpacing: 10,
      onReorder: (int oldIndex, int newIndex) {
        safeSetState(() {
          final String temp = _images[oldIndex];
          _images.removeAt(oldIndex);
          _images.insert(newIndex, temp);
        });
      },
      children: List<Widget>.generate(_total, (int index) {
        if (index >= widget.maxCount) return const SizedBox.shrink();

        if (index == _images.length) return _buildAddBtn;

        return _buildImg(index);
      }),
      footer: _footer,
    );
  }

  Widget? get _footer {
    return _total == widget.maxCount ? null : _buildAddBtn;
  }

  /// 构建图片
  Widget _buildImg(int index) {
    final String tag = feedHeroTag.replaceFirst('{item}', index.toString());

    return InkWell(
      onTap: () async => await _preView(index, tag),
      child: Stack(
        alignment: Alignment.topRight,
        children: <Widget>[
          AppImg.fitCover(
            heroTag: tag + index.toString(),
            url: _images[index],
            radius: 4,
            width: _itemSize,
            height: _itemSize,
          ),
          AppBtn(
            onTap: () async => await _removeImg(index),
            padding: const EdgeInsets.all(4),
            color: red(context),
            child: Icon(
              Icons.close_rounded,
              size: 14,
              color: white(context),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建添加图片按钮
  Widget get _buildAddBtn {
    return AppBtn(
      width: _itemSize,
      height: _itemSize,
      color: canvas(context),
      onTap: _pickImages,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Icon(
            Icons.add_photo_alternate_rounded,
            size: 50,
            color: disable(context).withOpacity(0.1),
          ),
          Text(
            '添加图片',
            style: TextStyle(
              fontSize: 11,
              color: disable(context),
            ),
          ),
        ],
      ),
    );
  }
}
